Day 13 리스트(배열)
Day13 13단계 20231101
1. n 번째 원소부터
- 내 풀이 (이틀간 문제를 안 풀었더니 머리가 굳었다)
- 길이가 (n번째~num_list 길이)인 새 배열을 만들고, 그 배열에 num_list의 n번째 이후부터 마지막까지의 요소를 넣었다.
class Solution {
public int[] solution(int[] num_list, int n) {
int[] answer = new int[num_list.length-n+1];
for(int i = n-1; i < num_list.length; i++) {
answer[i-(n-1)] = num_list[i];
}
return answer;
}
}
- 다른 사람 풀이 : Arrays.copyOfRange() 메소드를 사용해서 n번부터 마지막까지의 요소를 복사한 배열을 만들었다.
Arrays.copyOfRange(num_list, n-1, num_list.length);
2. 순서 바꾸기
- 내 풀이 : 배열 내에서 n번 이후 원소들을 맨 앞까지 순서 바꾸기(버블 정렬 이용)하여 문제에 맞는 배열로 만들었다.
class Solution {
public int[] solution(int[] num_list, int n) {
int temp = 0;
for(int i = 0; i < num_list.length - n; i++) {
for (int j = n+i; j >= 1+i; j--) {
temp = num_list[j];
num_list[j] = num_list[j-1];
num_list[j-1] = temp;
}
}
return num_list;
}
}
- 다른 사람 풀이 1 : 스트림으로 num_list만큼의 정수 길이 stream을 만든다. 이후 배열의 인덱스를 n만큼 더 더한 것에서 num_list 길이만큼을 나눈 나머지 값(배열의 길이가 num_list를 초과하지 않도록 설정)으로 만든 후 배열 요소를 넣었다.
IntStream.range(0, num_list.length).map(i -> num_list[(i + n) % num_list.length]).toArray();
- 다른 사람 풀이 2 : num_list와 동일한 길이의 배열을 하나 더 생성한 후, 배열의 첫 위치에 num_list 의 n 번째 요소부터 마지막까지 넣는다. 이후 num_list의 처음부터 (n-1)까지의 요소를 새 배열에 넣는다.
3. 왼쪽 오른쪽
- 내 풀이 : str_list에서 가장 먼저 등장하는 l이나 r을 찾아야 하므로, l 또는 r이 등장하는 인덱스와 각 문자를 저장한다. 그 후 switch를 사용해 조건별로 str_list를 자른다.
import java.util.*;
class Solution {
public String[] solution(String[] str_list) {
String str = "";
String[] answer = {};
int index = 0;
for(int i = 0; i < str_list.length; i++) {
if (str_list[i].equals("l")) {
str = str_list[i];
index = i;
break;
} else if (str_list[i].equals("r")) {
str = str_list[i];
index = i;
break;
}
}
switch (str) {
case "l" :
if(index != 0) { answer = Arrays.copyOfRange(str_list, 0, index); }
break;
case "r":
if(index != str_list.length - 1) { answer = Arrays.copyOfRange(str_list, index+1, str_list.length); }
break;
}
return answer;
}
}
- 다른 사람 풀이 : str_list에서 첫 등장한 l이나 r이 있으면 바로 배열을 자르고 return 해줘서 코드가 더 간략하다.
5. n개 간격의 원소들
- 내 풀이 : n이 배열의 길이의 배수인지 아닌지에 따라 새 배열의 크기를 지정. 일정 간격의 num_list의 배열을 새 배열에 추가
class Solution {
public int[] solution(int[] num_list, int n) {
int len = (num_list.length%n == 0) ? num_list.length/n : num_list.length/n+1;
int[] answer = new int[len];
int index = 0;
for(int i = 0; i < len; i++) {
answer[i] = num_list[index];
index += n;
}
return answer;
}
}
- 다른 사람 풀이 : for문 내부가 더 깔끔하게 정리되어 있다.
- 새 배열의 index를 아래처럼 index++로 지정해주고, i를 n씩 증가시키는 for문을 쓰는 것이 더 정돈되어 있다.
for (int i = 0;i < num_list.length; i+=n)
answer[idx++] = num_list[i];
return answer;